package com.lovelyj.trip_by_train.controller;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.lovelyj.trip_by_train.common.R;
import com.lovelyj.trip_by_train.entity.*;
import com.lovelyj.trip_by_train.service.ArriveService;
import com.lovelyj.trip_by_train.service.CoachService;
import com.lovelyj.trip_by_train.service.DailyTrainService;
import com.lovelyj.trip_by_train.service.TrainService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.time.LocalTime;
import java.util.List;
import java.util.Map;

@Slf4j
@RestController
@RequestMapping("/train")
public class TrainController {

    @Autowired
    private TrainService trainService;

    @Autowired
    private DailyTrainService dailyTrainService;

    @Autowired
    private ArriveService arriveService;

    @Autowired
    private CoachService coachService;


    @PutMapping("/create")
    public R<String> create(HttpServletRequest request,@RequestBody Map<String,Object> map) {
        log.info(map.toString());

        LambdaQueryWrapper<Train> queryWrapper = new LambdaQueryWrapper();
        queryWrapper.eq(Train::getTrainNum,map.get("trainNum").toString());
        int count=trainService.count(queryWrapper);
        if (count>0) {
            return R.error("车次号已存在");
        }
        Train train = new Train();
        train.setTrainNum(map.get("trainNum").toString());
        train.setStartStation(map.get("startStation").toString());
        train.setEndStation(map.get("endStation").toString());
        train.setDistance(Integer.parseInt(map.get("distance").toString()));
        String sTime = map.get("departureTime").toString();
        String eTime = map.get("endTime").toString();
        sTime=sTime.replace("Z", "");
        eTime=eTime.replace("Z", "");
        String[] time = sTime.split("T");
        LocalTime startTime = LocalTime.parse(time[1]).plusHours(8);
        log.info(startTime.toString());
        time = eTime.split("T");
        LocalTime endTime = LocalTime.parse(time[1]).plusHours(8);;
        log.info(endTime.toString());
        train.setStartTime(startTime);
        train.setEndTime(endTime);
        train.setDateDiff(Integer.parseInt(map.get("dateDiff").toString()));
        trainService.savePro(train);
        return R.success("添加成功");
    }

    @GetMapping("/page")
    public R<Page<Train>> selectPage(HttpServletRequest request, Integer page, String trainNum, String startStation, String endStation){
        log.info("selectPage..."+page);
        Page<Train> pageInfo=new Page<>(page,10);
        LambdaQueryWrapper<Train> queryWrapper=new LambdaQueryWrapper<>();

        queryWrapper.like(trainNum!=null,Train::getTrainNum,trainNum);
        queryWrapper.like(startStation!=null,Train::getStartStation,startStation);
        queryWrapper.like(endStation!=null,Train::getEndStation,endStation);
        trainService.page(pageInfo,queryWrapper);
        return R.success(pageInfo);
    }

    @Transactional
    @PostMapping("/deleteByIds")
    public R<String> deleteByIds(HttpServletRequest request,@RequestBody List<Long> selectedIds){

        log.info("deleteByIds...");

        for(Long id:selectedIds){
            String trainNum1=trainService.getById(id).getTrainNum();
            LambdaQueryWrapper<DailyTrain> lambdaQueryWrapper=new LambdaQueryWrapper<>();
            lambdaQueryWrapper.eq(DailyTrain::getTrainNum,trainNum1);
            if(dailyTrainService.count(lambdaQueryWrapper)>0){
               return R.error("该数据在每日车次中，无法删除");
            }
        }

        for(Long id:selectedIds){
            String trainNum1=trainService.getById(id).getTrainNum();
            LambdaQueryWrapper<Arrive> lambdaQueryWrapper1=new LambdaQueryWrapper<>();
            lambdaQueryWrapper1.eq(Arrive::getTrainNum,trainNum1);
            arriveService.remove(lambdaQueryWrapper1);
            LambdaQueryWrapper<Coach> lambdaQueryWrapper2=new LambdaQueryWrapper<>();
            lambdaQueryWrapper2.eq(Coach::getTrainNum,trainNum1);
            coachService.remove(lambdaQueryWrapper2);
        }

        trainService.removeByIds(selectedIds);

        return R.success("删除成功");
    }

    @DeleteMapping
    public R<String> deleteById(HttpServletRequest request,Long id){

        log.info("deleteById..."+id);
        String trainNum1=trainService.getById(id).getTrainNum();
        LambdaQueryWrapper<DailyTrain> lambdaQueryWrapper=new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(DailyTrain::getTrainNum,trainNum1);
        if(dailyTrainService.count(lambdaQueryWrapper)>0){
            return R.error("该数据在每日车次中，无法删除");
        }
        LambdaQueryWrapper<Arrive> lambdaQueryWrapper1=new LambdaQueryWrapper<>();
        lambdaQueryWrapper1.eq(Arrive::getTrainNum,trainNum1);
        arriveService.remove(lambdaQueryWrapper1);
        LambdaQueryWrapper<Coach> lambdaQueryWrapper2=new LambdaQueryWrapper<>();
        lambdaQueryWrapper2.eq(Coach::getTrainNum,trainNum1);
        coachService.remove(lambdaQueryWrapper2);

        trainService.removeById(id);
        return R.success("删除成功");
    }


    @Transactional
    @PutMapping("/update")
    public R<String> update(HttpServletRequest request,@RequestBody Map<String,Object> map){
        log.info("update...train"+map.toString());
        LambdaQueryWrapper<Train> queryWrapper = new LambdaQueryWrapper();
        queryWrapper.eq(Train::getTrainNum,map.get("trainNum").toString());
        int count=trainService.count(queryWrapper);
        if (count>1) {
            return R.error("车次号已存在");
        }
        Train train = new Train();
        train.setId(Long.parseLong(map.get("id").toString()));
        train.setTrainNum(map.get("trainNum").toString());
        train.setStartStation(map.get("startStation").toString());
        train.setEndStation(map.get("endStation").toString());
        String sTime = map.get("departureTime").toString();
        String eTime = map.get("endTime").toString();
        sTime=sTime.replace("Z", "");
        eTime=eTime.replace("Z", "");
        String[] time = sTime.split("T");
        LocalTime startTime = LocalTime.parse(time[1]).plusHours(8);
        log.info(startTime.toString());
        time = eTime.split("T");
        LocalTime endTime = LocalTime.parse(time[1]).plusHours(8);;
        log.info(endTime.toString());
        train.setStartTime(startTime);
        train.setEndTime(endTime);
        train.setDateDiff(Integer.parseInt(map.get("dateDiff").toString()));
        train.setDistance(Integer.parseInt(map.get("distance").toString()));
        Train originalTrain = trainService.getById(train.getId());
        LambdaQueryWrapper<DailyTrain> queryWrapper2 = new LambdaQueryWrapper<>();
        queryWrapper2.eq(DailyTrain::getTrainNum,originalTrain.getTrainNum());
        if(dailyTrainService.count(queryWrapper2)>0) {
            log.info("存在dailyTrain");
            return R.error("该车次在dailyTrain被使用，无法修改");
        }
        trainService.updatePro(train);
        return R.success("更新成功");
    }


    @GetMapping("/selectAll")
    public R<List<String>> selectMap(HttpServletRequest request){
        log.info("selectStations...");
        LambdaQueryWrapper<Train> queryWrapper=new LambdaQueryWrapper<>();
        queryWrapper.select(Train::getTrainNum);

        List<String> list = trainService.listObjs(
                new LambdaQueryWrapper<Train>().select(Train::getTrainNum),
                obj -> (String) obj // 类型转换
        );
        return R.success(list);
    }

}
